# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


import logging

_logger = logging.getLogger(__name__)


class FapiaoDraw(models.Model):
    _inherit = "fp.fapiao.draw"

    # state = fields.Selection(
    #     selection_add=[
    #         ('being_invalid', 'being_invalid'),  # 作废中. 临时状态
    #         ('be_invalid', 'be_invalid'),  # 已作废. 末状态  稳定状态
    #     ])

    nuonuo_serial_num = fields.Char(readonly=True,  help="开票请求后, 返回的序列号")

    nuonuo_api_status = fields.Selection(selection=[
        ('done', 'done'),  # 开票成功
        ('doing', 'doing'),  # 开票中
        ('signing', 'signing'),  # 开票成功签章中
        ('doerror', 'doerror'),  # 开票失败
        ('signerror', 'signerror'),  # 开票成功签章失败
        ('be_invalid', 'be_invalid'),  # 已作废
        ('being_invalid', 'being_invalid'),  # 作废中
    ], string="开票api状态", readonly=True,
        help="开票查询, 返回的开票结果")

    nuonuo_api_status_msg = fields.Char('状态消息', readonly=True)
    nuonuo_api_fail_cause = fields.Char('失败原因', readonly=True)

    def unlink(self):
        self2 = self.filtered(lambda r: not r.nuonuo_serial_num)

        return super(FapiaoDraw, self2).unlink()

    def action_request(self):
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search([
                ('id', 'in', self.ids),
                ('state', '=', 'draft'),
                ('nuonuo_serial_num', '=', False)])
        super(FapiaoDraw, self2).action_request()

    def action_query(self):
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search(
                [('id', 'in', self.ids),
                 ('state', 'in', ['requested', 'reread']),
                 ('nuonuo_serial_num', '!=', False)])

        super(FapiaoDraw, self2).action_query()

    def action_invalid(self):
        # # 发票 作废
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search(
                [('id', 'in', self.ids),
                 ('state', 'in', ['done']),
                 ('nuonuo_serial_num', '!=', False)])

        super(FapiaoDraw, self2).action_invalid()
